<template>
  <div class="login-container">
    <div class="top-container">
      <div class="logo">
        <img src="../../assets/images/logo.png" alt="">
      </div>
      <div class="user">
        <div class="user-text">
          <span>招商热线：<span style="color: #229AFF;">186-1139-8650</span></span>
        </div>
      </div>
    </div>
    <div class="login-box">
      <div class="login-form">
        <img class="qr-code" @click="changeQRHandler" src="../../assets/images/qr-code.png" alt="">
        <div class="qr-header">
          <h3>欢迎来到招商慧眼</h3>
        </div>
        <div v-if="changeLoginType" class="qr-body">
          <el-tabs v-model="activeName" stretch @tab-click="handleClick">
            <el-tab-pane label="账号登录" name="first">
              <el-form label-position="left" ref="loginRef" :model="loginForm" :rules="rules" label-width="auto"
                class="form-box" size="large" status-icon>
                <el-form-item prop="username">
                  <el-input :prefix-icon="User" v-model="loginForm.username" placeholder="请输入账号" />
                </el-form-item>
                <el-form-item prop="password">
                  <el-input type="password" :prefix-icon="Lock" v-model="loginForm.password" placeholder="请输入密码" />
                </el-form-item>
                <el-form-item class="ib" prop="smsNum">
                  <el-input v-model="loginForm.code" placeholder="请输入验证码" />
                  <img :src="codeUrl" @click="getCode" class="login-code-img" />
                </el-form-item>
                <el-form-item class="passwords">
                  <el-checkbox v-model="loginForm.rememberMe" label="记住密码" value="true" />
                  <span class="forgetPWD" @click="onForget">忘记密码?</span>
                </el-form-item>
                <el-form-item class="login-btn">
                  <el-button type="primary" @click.prevent="handleLogin(loginRef)">立即登录</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="手机登录" name="fourth">
              <el-form ref="ruleFormRef" :model="phoneForm" :rules="qrRules" label-width="auto" class="form-box"
                size="large" status-icon>
                <el-form-item prop="phoneNum">
                  <el-input :prefix-icon="Iphone" v-model="phoneForm.phoneNum" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item class="ib" prop="smsNum">
                  <el-input :prefix-icon="List" v-model="phoneForm.smsNum" placeholder="请输入短信验证码" />
                  <el-button type="primary" @click="smsHandler">获取验证码</el-button>
                </el-form-item>
                <el-form-item class="login-btn">
                  <el-button type="primary" @click="smsHandler">立即登录</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div v-else class="qr-body-sys">
          <h3>手机微信扫码登录</h3>
          <img src="../../assets/images/qr2.png" alt="">
          <el-button type="primary" @click="smsHandler">立即登录</el-button>
        </div>
        <div class="qr-footer">
          <p>登陆即视为您已阅读并同意 <span style="color: #006EFF;">《服务条款》</span> 和 x<span style="color: #006EFF;">《隐私政策》</span></p>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from "vue"
import { useRouter, useRoute } from "vue-router"
import { Iphone } from "@element-plus/icons-vue"
import { List } from "@element-plus/icons-vue"
import { User } from "@element-plus/icons-vue"
import { Lock } from "@element-plus/icons-vue"
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import useUserStore from '@/stores/modules/user'
import { ElMessage } from 'element-plus'

const loginRef = ref()
const activeName = ref('first')
const changeLoginType = ref(true)
const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const codeUrl = ref("");
const loading = ref(false);

// 验证码开关
const captchaEnabled = ref(true);

/**
 * 用户登录
 */
const handleLogin = (formEl) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      // 调用action的登录方法
      userStore.login(loginForm.value).then(() => {
        const query = route.query;
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur];
          }
          return acc;
        }, {});
        router.push({ path: "/", query: otherQueryParams })
        // router.push({ path: redirect.value || "/", query: otherQueryParams });
      }).catch(() => {
        loading.value = false;
        // 重新获取验证码
        if (captchaEnabled.value) {
          getCode();
        }
      });
    }
  });
}

onMounted(() => {
  getCode()
  getCookie()
})

/**
 * 获取验证码
 */
const getCode = () => {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      loginForm.value.uuid = res.uuid;
    }
  });
}

/**
 * 记住密码
 */
const getCookie = () => {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  };
}

const loginForm = ref({
  username: '',
  password: '',
  code: '',
  rememberMe: false,
  uuid: ''
})

const phoneForm = reactive({
  phoneNum: '',
  smsNum: ''
})

const changeQRHandler = () => {
  changeLoginType.value = !changeLoginType.value
}

const handleClick = (tab, event) => {
  console.log(tab, event)
}

const smsHandler = () => {

}

const onForget = () => {
  router.push("/register")
}

const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '长度不能小于4个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '长度不能小于6个字符', trigger: 'blur' },
  ]
})

const qrRules = reactive({
  phoneNum: [
    { required: true, message: '请输入手机号码', trigger: 'blur' }
  ],
  smsNum: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
  ]
})

</script>
<style lang="less" scoped>
.login-container {

  width: 100%;
  height: 100vh;
  background: url("../../assets/images/login-bg.png") no-repeat;
  background-position: center;
  background-size: cover;

  .top-container {
    width: 100%;
    height: 60px;
    line-height: 60px;
    background: #fff;
    position: absolute;
    box-shadow: 0px 3px 6px 0px rgba(72, 94, 132, 0.1);
    z-index: 999;
    display: flex;

    .logo {
      display: flex;
      justify-content: center;
      align-items: center;

      img {
        display: block;
        cursor: pointer;
        height: 30px;
      }
    }

    .user {
      flex: 1;
      display: flex;
      justify-content: flex-end;
      align-items: center;

      .user-icon {
        margin-right: 10px;

        img {
          display: block;
          width: 40px;
          height: 40px;
          border-radius: 50%;
        }
      }

      .user-text {
        span {
          margin-right: 10px;
          font-weight: 700;
          font-size: 16px;
        }
      }
    }
  }

  .login-box {
    width: 100%;
    height: 100vh;
    display: flex;
    align-items: center;

    .login-form {
      position: absolute;
      margin-top: -60px;
      width: 400px;
      right: 100px;
      padding: 20px 50px;
      background: #fff;
      box-shadow: 0 0 15px rgba(100, 100, 100, .2);

      .qr-code {
        width: 60px;
        height: 60px;
        position: absolute;
        right: 0;
        top: 0;
      }

      .qr-header {
        padding: 20px 0;

        h3 {
          text-align: center;
          font-size: 26px;
          color: #404040;
        }
      }

      :deep(.el-tabs__header) {
        .el-tabs__nav-wrap:after {
          height: 0;
        }

        .el-tabs__item.is-active {
          color: #394565;
        }

        .el-tabs__item {
          color: #989DA1;
        }
      }

      .qr-body {
        .form-box {
          margin: 20px 0;

          .ib {
            .el-form-item__content {
              .el-input {
                flex: 1;
                margin-right: 10px;
              }
            }
          }

          .passwords {
            :deep(.el-form-item__content) {
              justify-content: space-between;
              color: #989DA1;
              cursor: pointer;
            }
          }

          .login-btn {
            margin-top: 30px;

            button {
              flex: 1;
            }
          }
        }
      }

      .qr-body-sys {
        text-align: center;

        h3 {
          font-size: 18px;
          color: #394565;
        }

        img {
          width: 177px;
          height: 177px;
          margin: 20px 0;
        }

        button {
          height: 40px;
          width: 100%;
        }
      }

      .qr-footer {
        margin: 30px 0;
        text-align: center;

        p {
          font-size: 12px;
        }
      }
    }
  }
}

.login-code-img {
  height: 38px;
  width: 100px;
  padding-left: 12px;
}
</style>
